package com.zhongshengnetwork.rightbe.wzt.activity;

import androidx.annotation.NonNull;
import androidx.appcompat.app.AppCompatActivity;
import androidx.recyclerview.widget.DefaultItemAnimator;
import androidx.recyclerview.widget.ItemTouchHelper;
import androidx.recyclerview.widget.LinearLayoutManager;
import androidx.recyclerview.widget.RecyclerView;

import android.content.Intent;
import android.os.Bundle;
import android.view.View;

import com.scwang.smartrefresh.layout.SmartRefreshLayout;
import com.scwang.smartrefresh.layout.api.RefreshLayout;
import com.scwang.smartrefresh.layout.constant.RefreshState;
import com.scwang.smartrefresh.layout.constant.SpinnerStyle;
import com.scwang.smartrefresh.layout.footer.ClassicsFooter;
import com.scwang.smartrefresh.layout.header.BezierRadarHeader;
import com.scwang.smartrefresh.layout.listener.OnLoadMoreListener;
import com.zhongshengnetwork.rightbe.Constant.APIKey;
import com.zhongshengnetwork.rightbe.Constant.Constant;
import com.zhongshengnetwork.rightbe.CustomApplication;
import com.zhongshengnetwork.rightbe.R;
import com.zhongshengnetwork.rightbe.common.AppThemeUtils;
import com.zhongshengnetwork.rightbe.common.BroadcastDefine;
import com.zhongshengnetwork.rightbe.common.CommonUtils;
import com.zhongshengnetwork.rightbe.common.GsonTools;
import com.zhongshengnetwork.rightbe.common.TopBarView;
import com.zhongshengnetwork.rightbe.common.activity.AppBaseActivity;
import com.zhongshengnetwork.rightbe.common.loading.KyLoadingBuilder;
import com.zhongshengnetwork.rightbe.common.topgrid.activity.TopGridActivity;
import com.zhongshengnetwork.rightbe.common.utils.ToastUtil;
import com.zhongshengnetwork.rightbe.gsonmodel.CommonModel;
import com.zhongshengnetwork.rightbe.gsonmodel.WeiShuContentDetailModel;
import com.zhongshengnetwork.rightbe.https.HttpCallBack;
import com.zhongshengnetwork.rightbe.https.HttpsUtils;
import com.zhongshengnetwork.rightbe.wzt.view.ItemDragCallback;
import com.zhongshengnetwork.rightbe.wzt.view.WZTOrderRecyclerAdapter;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;

public class WZTContentOrderActivity extends AppBaseActivity implements TopBarView.onTitleBarClickListener {

    private static final int REQUEST_PUBLISH = 1002;
    private static final int REQUEST_EDIT = 1003;
    public static final int REQUEST_CONTENT_EDIT = 1004;
    public static final int REQUEST_CONTENT_ORDER = 1005;

    private long id;
    private Byte contentType = 0;
    public boolean canBrowseAll = false;
    private String wztUserId = "";
    private TopBarView topbar;

    private RecyclerView listview;
    private WZTOrderRecyclerAdapter wztOrderRecyclerAdapter;
    private RefreshLayout mRefreshLayout;
    private List<WeiShuContentDetailModel> list;
    private long maxOrderId = 0;
    private List<String> orderIds;
    private List<String> langIds;

    private int pageindex = 0;
    private static final int Records = 20;

    boolean isSaving = false;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_wztcontent_order);

        id = getIntent().getLongExtra("id", 0);
        contentType = getIntent().getByteExtra("contentType", Byte.valueOf("0"));
        canBrowseAll = getIntent().getBooleanExtra("canBrowseAll", false);
        wztUserId = getIntent().getStringExtra("wztUserId");

        topbar = (TopBarView)findViewById(R.id.topbar);
        topbar.getRightView().setVisibility(View.GONE);
        topbar.setClickListener(this);
        topbar.getRightTextView().setText("保存");
        topbar.getRightTextView().setTextSize(18);
        topbar.getRightTextView().setTextColor(getResources().getColor(R.color.mainColor));
        topbar.getRightTextView().setClickable(true);
        topbar.getRightTextView().setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                save();
            }
        });

        if (list == null){
            list = new ArrayList<WeiShuContentDetailModel>();
        }

        if (langIds == null){
            langIds = new ArrayList<String>();
        }

        if (orderIds == null){
            orderIds = new ArrayList<String>();
        }

        listview=(RecyclerView) findViewById(R.id.wzt_listview);
        LinearLayoutManager layoutManager = new LinearLayoutManager(WZTContentOrderActivity.this);
        listview.setLayoutManager(layoutManager);
        listview.setHasFixedSize(false);
        listview.setNestedScrollingEnabled(false);
        ((DefaultItemAnimator) listview.getItemAnimator()).setSupportsChangeAnimations(false);//解决局部更新闪烁问题
        wztOrderRecyclerAdapter = new WZTOrderRecyclerAdapter(list, WZTContentOrderActivity.this, listview, contentType, canBrowseAll, wztUserId);
        listview.setAdapter(wztOrderRecyclerAdapter);

        //长按拖动排序
        ItemDragCallback callback = new ItemDragCallback(wztOrderRecyclerAdapter);
        ItemTouchHelper helper = new ItemTouchHelper(callback);
        helper.attachToRecyclerView(listview);

        mRefreshLayout = (SmartRefreshLayout)findViewById(R.id.refreshLayout);
        //设置 Header 为 贝塞尔雷达 样式
        mRefreshLayout.setRefreshHeader(new BezierRadarHeader(WZTContentOrderActivity.this).setEnableHorizontalDrag(true));//BezierRadarHeader
        //设置 Footer 为 球脉冲 样式
        mRefreshLayout.setRefreshFooter(new ClassicsFooter(WZTContentOrderActivity.this).setSpinnerStyle(SpinnerStyle.FixedBehind));//BallPulseFooter ClassicsFooter
        mRefreshLayout.setPrimaryColors(AppThemeUtils.getInstance().getRefreshBackgroundColor(),AppThemeUtils.getInstance().getRefreshAccessColor());
        mRefreshLayout.setEnableRefresh(false);//禁用刷新
        mRefreshLayout.setEnableLoadMore(false);//启用加载
        mRefreshLayout.setOnLoadMoreListener(new OnLoadMoreListener() {
            @Override
            public void onLoadMore(@NonNull RefreshLayout refreshLayout) {
                getData(false);
            }
        });
        getData(true);
    }

    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        if ((requestCode == REQUEST_PUBLISH || requestCode == REQUEST_CONTENT_EDIT) && resultCode == RESULT_OK){
            if (data != null){
                boolean isBacken = data.getBooleanExtra("isBacken", false);
                if (isBacken == true){
                    //发送通知
                    Intent mIntent = new Intent(BroadcastDefine.WZTContentStartPublish_Notify_Action);
                    //发送广播
                    sendBroadcast(mIntent);
                    return;
                }
            }
        }
    }

    /**
     * 点击了返回导航按钮
     */
    @Override
    public void onBackClick() {
        finish();
        //Toast.makeText(LangDetailActivity.this, "你点击了左侧按钮", Toast.LENGTH_LONG).show();

    }

    /**
     * 点击了右边导航按钮
     */
    @Override
    public void onRightClick() {

    }

    public void getData(boolean isFirst){

        if (isFirst == true){
            pageindex = 0;
        }

        new Thread(new Runnable() {
            @Override
            public void run() {
                final HashMap<String, String> map = new HashMap<String, String>();
                map.put(APIKey.tokenKey, CommonUtils.formatString(CustomApplication.loginModel.getToken()));
                map.put("dataId",""+id);
                map.put("dataType", "0");
                map.put("pageIndex",pageindex+"");
                map.put("pageRecord",Records+"");
                HttpsUtils.miniAppDo(map, "weishu/theme/list.do", new HttpCallBack() {
                    @Override
                    public void onSuccess(String data) {
                        final CommonModel commonModel = GsonTools.getCommonModel(data);
                        if (commonModel.getFlag().equals("1")){
                            final List<WeiShuContentDetailModel> l = GsonTools.getWeiShuContentDetailModelList(data);
                            runOnUiThread(new Runnable() {
                                @Override
                                public void run() {
                                    if (mRefreshLayout.getState() == RefreshState.Loading){
                                        mRefreshLayout.finishLoadMore();
                                    }
                                    int fromposition = list.size();
                                    if (l != null && l.size() > 0){
                                        for (int i = 0; i < l.size(); i++){
                                            WeiShuContentDetailModel m = l.get(i);
                                            if (maxOrderId == 0){
                                                maxOrderId = m.getId();
                                            }
                                            if (m.getId() > maxOrderId){
                                                maxOrderId = m.getId();
                                            }
                                        }
                                        if (l.size() >= Records){
                                            mRefreshLayout.setEnableLoadMore(true);
                                        }else {
                                            mRefreshLayout.setEnableLoadMore(false);
                                        }
                                        if (pageindex == 0){
                                            list.clear();
                                        }
                                        list.addAll(l);
                                    }else {
                                        mRefreshLayout.setEnableLoadMore(false);
                                    }
                                    if (pageindex == 0){
                                        wztOrderRecyclerAdapter.notifyDataSetChanged();
                                    }else {
                                        wztOrderRecyclerAdapter.notifyItemRangeChanged(fromposition, l.size());
                                    }
                                    if (l != null && l.size() > 0){
                                        pageindex += 1;
                                    }

                                }
                            });
                        }else {
                            runOnUiThread(new Runnable() {
                                @Override
                                public void run() {
                                    mRefreshLayout.finishLoadMore();
                                    CustomApplication.showTip(commonModel, WZTContentOrderActivity.this);
                                }
                            });
                        }
                    }

                    @Override
                    public void onError(String msg) {
                        runOnUiThread(new Runnable() {
                            @Override
                            public void run() {
                                mRefreshLayout.finishLoadMore();
                            }
                        });
                    }
                });
            }
        }).start();

    }

    private void save(){
        if (list == null || list.size() == 0){
            return;
        }
        if (isSaving == true){
            return;
        }
        isSaving = true;
        KyLoadingBuilder dialog = new KyLoadingBuilder(WZTContentOrderActivity.this);
        dialog.setIcon(R.drawable.loading04);
        dialog.setText("正在保存...");
        dialog.setOutsideTouchable(false);//点击空白区域是否关闭
        dialog.setBackTouchable(true);//按返回键是否关闭
        dialog.show();

        langIds.clear();
        orderIds.clear();
        for (int i = 0; i < list.size(); i++){
            WeiShuContentDetailModel m = list.get(i);
            langIds.add(m.getId()+"");
            orderIds.add(maxOrderId+"");
            maxOrderId -= 1;
        }

        final HashMap<String, String> map = new HashMap<String, String>();
        if (CommonUtils.isLogin() == true){
            map.put(APIKey.tokenKey, CustomApplication.loginModel.getToken());
        }else {
            ToastUtil.show(WZTContentOrderActivity.this, "登录过期，请重新登录");
            return;
        }
        map.put("orderIds", CommonUtils.listToString(orderIds));
        map.put("langIds", CommonUtils.listToString(langIds));
        String url = "weishu/content/rank.do";
        HttpsUtils.miniAppDo(map, url, new HttpCallBack() {
            @Override
            public void onSuccess(String data) {
                isSaving = false;
                CommonModel commonModel = GsonTools.getCommonModel(data);
                if (commonModel.getFlag().equals("1")){
                    ToastUtil.show(WZTContentOrderActivity.this, "保存成功");
                    Intent intent = new Intent();
                    intent.putExtra("isOrdered", true);
                    setResult(RESULT_OK, intent);
                    finish();
                }else {
                    if (commonModel.getCode().equals(Constant.UserReturnCode.CODE_10011)) {//登录过期
                        CustomApplication.showTip(commonModel, WZTContentOrderActivity.this);
                        return;
                    }
                    ToastUtil.show(WZTContentOrderActivity.this, commonModel.getMsg());
                }
            }

            @Override
            public void onError(String msg) {
                 isSaving = false;
                 runOnUiThread(new Runnable() {
                     @Override
                     public void run() {
                         dialog.dismiss();
                         ToastUtil.show(WZTContentOrderActivity.this, "保存失败");
                     }
                 });
            }
        });

    }

}
